package com.maple.common.widget

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.TextUtils
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.maple.common.R
import com.maple.common.base.BaseViewHolder
import com.maple.common.databinding.SpinnerPopRecycleBinding
import com.maple.common.databinding.SpinnerSimpleTextBinding
import com.maple.common.databinding.SpinnerTextViewBinding
import com.maple.common.ext.divider
import com.maple.common.utils.StringUtils

/**
 * Tip:
 * Create by SeVen on 2023/9/9 17:22
 */
class SpinnerTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private var viewBinding: SpinnerTextViewBinding = SpinnerTextViewBinding.inflate(
        LayoutInflater.from(context), this, true
    )

    private var inputList: MutableList<String>? = null

    init {

        obtainAttributes(context, attrs)
    }

    private fun obtainAttributes(context: Context, attrs: AttributeSet?) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.SpinnerTextView)
        val titleText = ta.getString(R.styleable.SpinnerTextView_sp_titleText)
        val titleTextColor = ta.getColor(
            R.styleable.SpinnerTextView_sp_titleColor,
            ContextCompat.getColor(context, R.color.white)
        )
        val titleSize = ta.getDimension(R.styleable.SpinnerTextView_sp_titleSize, sp2px(14f))
        val alignSize = ta.getInt(R.styleable.SpinnerTextView_sp_alignSize, 3)

        val inputText = ta.getString(R.styleable.SpinnerTextView_sp_inputText)
        val inputColor = ta.getColor(
            R.styleable.SpinnerTextView_sp_inputColor,
            ContextCompat.getColor(context, R.color.white)
        )
        val inputSize = ta.getDimension(R.styleable.SpinnerTextView_sp_inputSize, sp2px(14f))
        val isArrowShow = ta.getBoolean(R.styleable.SpinnerTextView_sp_isShowArrow, false)
        val isInput = ta.getBoolean(R.styleable.SpinnerTextView_sp_isInput, true)
        ta.recycle()

        if (!TextUtils.isEmpty(titleText)) {
            viewBinding.tvName.text = titleText?.let { StringUtils.justifyString(it, alignSize) }
            viewBinding.tvName.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize)
            viewBinding.tvName.setTextColor(titleTextColor)
        }

        viewBinding.etInput.clearFocus()
        viewBinding.etInput.isFocusableInTouchMode = isInput
        viewBinding.etInput.focusable = FOCUSABLE_AUTO

        if (!TextUtils.isEmpty(inputText)) {
            viewBinding.etInput.setText(inputText)
            viewBinding.etInput.setTextColor(inputColor)
            viewBinding.etInput.setTextSize(TypedValue.COMPLEX_UNIT_PX, inputSize)
        }

        if (isArrowShow) {
            viewBinding.ivArrow.visibility = View.VISIBLE
        } else {
            viewBinding.ivArrow.visibility = View.GONE
        }

        viewBinding.ivArrow.setOnClickListener {
            inputList?.let {
                val list = mutableListOf<String>()
                list.addAll(it)
                val popupWindow = SpinnerPopupWindow(context, list)
                popupWindow.width = viewBinding.llContentLayout.measuredWidth
                popupWindow.showPopupWindow(viewBinding.llContentLayout)
                popupWindow.setOnClickListener(object : SpinnerPopupWindow.OnClickListener {
                    override fun onClick(clickContent: String) {
                        viewBinding.etInput.setText(clickContent)
                    }
                })
            }
        }
    }

    fun getInputContent(): String {
        viewBinding.etInput.text.let {
            return it.toString()
        }
    }

    fun setInputContent(content: String) {
        viewBinding.etInput.setText(content)
    }

    fun setInputSelectList(inputList: MutableList<String>) {
        this.inputList = inputList
    }

    private fun sp2px(spValue: Float): Float {
        val scale = context.resources.displayMetrics.density
        return spValue * scale + 0.5f
    }
}


/**
 * Tip:
 * Create by SeVen on 2023/9/9 17:34
 */
class SpinnerPopupWindow @JvmOverloads constructor(
    context: Context,
    list: MutableList<String>,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : PopupWindow(context, attrs, defStyleAttr) {
    private var popRecycleBinding: SpinnerPopRecycleBinding =
        SpinnerPopRecycleBinding.inflate(LayoutInflater.from(context))

    init {
        this.width = ViewGroup.LayoutParams.WRAP_CONTENT
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        this.isFocusable = true
        this.isOutsideTouchable = true
        this.update()
        this.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        this.contentView = popRecycleBinding.root

        initData(context, list)
    }

    private fun initData(context: Context, list: MutableList<String>) {
        val spinnerPopAdapter = SpinnerPopAdapter()
        popRecycleBinding.rvPop.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            divider(ContextCompat.getColor(context, R.color.white))
            setHasFixedSize(true)
            isNestedScrollingEnabled = false
            adapter = spinnerPopAdapter
        }
        spinnerPopAdapter.addAll(list)
        spinnerPopAdapter.setOnItemClickListener { adapter, _, position ->
            adapter.getItem(position)?.let { onClickListener?.onClick(it) }
            dismissPopupWindow()
        }
    }

    fun showPopupWindow(parent: View) {
        if (!this.isShowing) {
            this.showAsDropDown(parent, parent.layoutParams.width, 0)
        } else {
            this.dismiss()
        }
    }

    fun showPopupWindow(parent: View, gravity: Int) {
        if (!this.isShowing) {
            this.showAtLocation(parent, gravity, 0, 0)
            this.showAsDropDown(parent, parent.layoutParams.width, 0)
        } else {
            this.dismiss()
        }
    }

    fun dismissPopupWindow() {
        if (this.isShowing) {
            this.dismiss()
        }
    }

    private var onClickListener: OnClickListener? = null

    fun setOnClickListener(onClickListener: OnClickListener) {
        this.onClickListener = onClickListener
    }

    interface OnClickListener {
        fun onClick(clickContent: String)
    }
}

/**
 * Tip:
 * Create by SeVen on 2023/9/9 17:34
 */
class SpinnerPopAdapter : BaseQuickAdapter<String, SpinnerPopAdapter.VH>() {

    class VH(
        parent: ViewGroup,
        val binding: SpinnerSimpleTextBinding = SpinnerSimpleTextBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
    ) : BaseViewHolder(binding.root)

    override fun onBindViewHolder(holder: VH, position: Int, item: String?) {
        holder.binding.tvSpinnerText.text = item
    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup,
        viewType: Int
    ): VH {
        return VH(parent)
    }
}